package com.tanhua.dubbo.api;

import com.tanhua.dubbo.utils.IdWorker;

import com.tanhua.model.mongo.Video;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;
@DubboService
public class VideoApiImpl implements VideoApi{
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Override
    public String save(Video video) {
        //1、设置属性
        video.setVid(idWorker.getNextId("video"));
        video.setCreated(System.currentTimeMillis());
        //2、调用方法保存对象
        mongoTemplate.save(video);
        //3、返回对象id
        return video.getId().toHexString();
    }

    @Override
    public List<Video> findMovementsByVids(List<Long> vids) {
        Query query = Query.query(Criteria.where("vid").in(vids));
        return mongoTemplate.find(query,Video.class);
    }

    @Override
    public List<Video> queryVideoList(int page, Integer pagesize) {
        Query query = new Query().limit(pagesize).skip((page -1) * pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        return mongoTemplate.find(query,Video.class);
    }

    /*视频列表:分页查询*/
    @Override
    public PageResult findAll(Integer page, Integer pagesize) {

        long count = mongoTemplate.count(new Query(), Video.class);

        Query query=new Query().with(Sort.by(Sort.Order.desc("created")))
                .limit(pagesize).skip((page-1)*pagesize);
        List<Video> list = mongoTemplate.find(query, Video.class);

        return  new PageResult(page,pagesize, count,list);
    }

    @Override
    public PageResult findByUserId(Integer page, Integer pagesize, Long userId) {

        Query s = Query.query(Criteria.where("usrId").is(userId)).with(Sort.by(Sort.Order.desc("created")))
                .limit(pagesize).skip((page - 1) * pagesize);
        long count = mongoTemplate.count(s, Video.class);
        List<Video> list = mongoTemplate.find(s, Video.class);

        return  new PageResult(page,pagesize, count,list);
    }

}
